package xiaoqi.qingyue.api.basic.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import xiaoqi.qingyue.api.basic.user.model.entity.User;
import xiaoqi.qingyue.api.basic.user.model.entity.UserInfo;
import xiaoqi.qingyue.api.basic.user.mapper.UserInfoMapper;
import xiaoqi.qingyue.api.basic.user.mapper.UserMapper;
import xiaoqi.qingyue.api.basic.user.model.dto.UserDto;
import xiaoqi.qingyue.api.basic.user.model.query.LoginQuery;

import java.util.List;

/**
 * @author 92110
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final UserInfoMapper userInfoMapper;

    @Override
    public String login(@NonNull LoginQuery loginQuery) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getUsername, loginQuery.getUsername())
                .eq(User::getPassword, loginQuery.getPassword())
                .eq(User::getStatus, '1');
        User user = userMapper.selectOne(queryWrapper);
        return user.getUsername();
    }

    @Override
    public UserDto getUserInfo(@NonNull String username) {
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username);
        User user = userMapper.selectOne(userQueryWrapper);
        LambdaQueryWrapper<UserInfo> infoQueryWrapper = new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserId, user.getId());
        UserInfo userInfo = userInfoMapper.selectOne(infoQueryWrapper);
        return new UserDto(user, userInfo);
    }

    @Override
    public List<UserDto> getUserList() {
        List<User> userList = userMapper.selectList(null);
        return userList.stream().map(user -> {
            LambdaQueryWrapper<UserInfo> infoQueryWrapper = new LambdaQueryWrapper<UserInfo>()
                    .eq(UserInfo::getUserId, user.getId());
            UserInfo userInfo = userInfoMapper.selectOne(infoQueryWrapper);
            return new UserDto(user, userInfo);
        }).toList();
    }

    @Override
    public String updateUser(User user) {
        userMapper.updateById(user);
        return user.getUsername();
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.update(new User(id, '0'), new UpdateWrapper<User>().eq("user_id", id));
    }

    @Override
    public void recoverUser(Integer id) {
        userMapper.update(new User(id, '1'), new UpdateWrapper<User>().eq("user_id", id));
    }

    @Override
    public void insertUser(UserDto userDto) {
        userMapper.insert(userDto.getUser());
        // TODO 添加用户信息
        // userInfoMapper.insert(userDto.getInfo());
    }
}
